package com.ushio.capsuleservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ushio.capsuleservice.mapper.ContainerMapper;
import com.ushio.capsuleservice.model.entity.Container;
import com.ushio.capsuleservice.service.ContainerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 时间容器服务实现类
 *
 */
@Slf4j
@Service
public class ContainerServiceImpl extends ServiceImpl<ContainerMapper, Container> implements ContainerService {

    @Override
    public List<Container> findByUserId(Long userId) {
        return lambdaQuery()
                .eq(Container::getUserId, userId)
                .list();
    }

    @Override
    public boolean deleteByUserId(Long userId) {
        return lambdaUpdate()
                .eq(Container::getUserId, userId)
                .remove();
    }

    @Override
    public Container createContainer(Container container) {
        container.setStatus(1); // 进行中
        container.setCreatedTime(LocalDateTime.now());
        container.setUpdatedTime(LocalDateTime.now());
        
        save(container);
        return container;
    }
    
    @Override
    public IPage<Container> getUserContainers(Long userId, int page, int size, Integer status, 
                                              String keyword, String category, String startDate, 
                                              String endDate, BigDecimal minScore, BigDecimal maxScore) {
        Page<Container> pageParam = new Page<>(page, size);
        QueryWrapper<Container> queryWrapper = new QueryWrapper<>();
        
        queryWrapper.eq("user_id", userId);
        
        // 状态筛选
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        
        // 关键词搜索（标题或描述）
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                .like("title", keyword)
                .or()
                .like("description", keyword)
            );
        }
        
        // 分类筛选
        if (category != null && !category.trim().isEmpty()) {
            queryWrapper.eq("category", category);
        }
        
        // 日期范围筛选
        if (startDate != null && !startDate.trim().isEmpty()) {
            queryWrapper.ge("created_time", startDate + " 00:00:00");
        }
        if (endDate != null && !endDate.trim().isEmpty()) {
            queryWrapper.le("created_time", endDate + " 23:59:59");
        }
        
        // 评分范围筛选（包含未评分 NULL 的记录）
        // 说明：直接使用 ge/le 会排除 NULL；这里用 COALESCE 将 NULL 视为默认值参与比较
        // 默认下限使用 0（或业务最小值），默认上限使用 10（或业务最大值）
        if (minScore != null) {
            // COALESCE(effectiveness_score, 0) >= minScore
            queryWrapper.apply("COALESCE(effectiveness_score, 0) >= {0}", minScore);
        }
        if (maxScore != null) {
            // COALESCE(effectiveness_score, 10) <= maxScore
            queryWrapper.apply("COALESCE(effectiveness_score, 10) <= {0}", maxScore);
        }
        
        queryWrapper.orderByDesc("created_time");
        
        return page(pageParam, queryWrapper);
    }
    
    @Override
    public Container getContainerDetail(Long containerId) {
        Container container = getById(containerId);
        if (container != null && container.getStatus() != 0) {
            return container;
        }
        return null;
    }
    
    @Override
    public Container updateContainer(Long containerId, Container container) {
        Container existingContainer = getById(containerId);
        if (existingContainer == null) {
            throw new RuntimeException("时间容器不存在");
        }
        //创建一个现在的时间给到endTime 2025-09-21 21:25:15 格式
        existingContainer.setEndTime(LocalDateTime.now());
        //计算创建时间和结束时间的差值给到elapsed_time（单位：秒）
        Duration duration = Duration.between(existingContainer.getStartTime(), existingContainer.getEndTime());
        existingContainer.setElapsedTime((int) duration.getSeconds());
        log.info("ni yao xiu gai elapsed_time:{}",(int) duration.getSeconds());
        updateById(existingContainer);
//        Container existingContainer = getById(containerId);
//        if (existingContainer == null) {
//            throw new RuntimeException("时间容器不存在");
//        }
//
//        existingContainer.setTitle(container.getTitle());
//        existingContainer.setDescription(container.getDescription());
//        existingContainer.setTags(container.getTags());
//        existingContainer.setUpdatedTime(LocalDateTime.now());
//
//        updateById(existingContainer);
        return existingContainer;
    }
    
    @Override
    public Container endContainer(Long containerId) {
        Container container = getById(containerId);
        if (container == null) {
            throw new RuntimeException("时间容器不存在");
        }
        
        container.setStatus(2); // 已结束
        container.setEndTime(LocalDateTime.now());
        container.setUpdatedTime(LocalDateTime.now());
        
        updateById(container);
        return container;
    }
    
    @Override
    public boolean deleteContainer(Long containerId) {
        Container container = getById(containerId);
        if (container == null) {
            throw new RuntimeException("时间容器不存在");
        }
        
        container.setStatus(0); // 已删除
        container.setUpdatedTime(LocalDateTime.now());
        
        return updateById(container);
    }
    
    @Override
    public long getActiveContainerCount(Long userId) {
        QueryWrapper<Container> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("status", 1); // 进行中
        return count(queryWrapper);
    }
    
    @Override
    public List<Container> getContainersByPlanId(Long planId) {
        return lambdaQuery()
                .eq(Container::getPlanId, planId)
//                .ne(Container::getStatus, 0) // todo 暂时没写删除---排除已删除的容器
                .orderByDesc(Container::getCreatedTime)
                .list();
    }
}
